package log

import (
	"GinTemplate/conf"
	"GinTemplate/utils/formatTime"
	"GinTemplate/utils/system"
	"fmt"
	"github.com/gin-gonic/gin"
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"github.com/rifflock/lfshook"
	"github.com/sirupsen/logrus"
	"net/http"
	"os"
	"time"
)

var logger *logrus.Logger

func InitLog1() {
	//日志实例化
	logger = logrus.New()
	//读取写入文件目录(读取配置文件的日志目录与日志名称)
	filepath := conf.Cfg.Server.LogPath
	err := system.CreateMoreFolder(filepath)
	if err != nil {
		fmt.Println("create error")
	}
	filename := "app-" + time.Now().Format(formatTime.TimeShortFormat) + ".log"
	//fileName := path.Join(path1, filePath)

	//拼接写入文件路径
	file := filepath + filename
	fmt.Println(file)
	//设置输出到文件
	logger.Out = os.Stdout
	//设置日志级别
	logger.SetLevel(logrus.DebugLevel)
	//设置日志格式
	logger.SetFormatter(&logrus.JSONFormatter{
		TimestampFormat: formatTime.TimeFullFormat,
	})

	//设置日志切割 rotatelogs
	logWriter, _ := rotatelogs.New(
		file,
		//生成软链 指向最新的日志文件
		//rotatelogs.WithLinkName(file),
		//文件最大保存时间
		rotatelogs.WithMaxAge(7*24*time.Hour),
		//设置日志切割时间间隔(1天)(隔多久分割一次)
		rotatelogs.WithRotationTime(24*time.Hour),
	)

	writeMap := lfshook.WriterMap{
		logrus.InfoLevel:  logWriter,
		logrus.FatalLevel: logWriter,
		logrus.DebugLevel: logWriter,
		logrus.WarnLevel:  logWriter,
		logrus.ErrorLevel: logWriter,
		logrus.PanicLevel: logWriter,
	}

	//lfHook := lfshook.NewHook(writeMap, &logrus.JSONFormatter{
	lfHook := lfshook.NewHook(writeMap, &logrus.TextFormatter{
		TimestampFormat: formatTime.TimeFullFormat,
		DisableColors:   false,
	})

	logger.AddHook(lfHook)
}

func LoggerToFile1() gin.HandlerFunc {
	InitLog1()
	return func(c *gin.Context) {
		//开始时间
		startTime := time.Now()
		//处理请求
		c.Next()
		//结束时间
		endTime := time.Now()
		//执行时间
		latencyTime := endTime.Sub(startTime)

		//请求方式
		reqMethod := c.Request.Method

		//请求路由
		reqUri := c.Request.RequestURI

		//状态码
		statusCode := c.Writer.Status()

		//请求IP
		ClientIp := c.ClientIP()

		//日志格式
		entry := logger.WithFields(logrus.Fields{
			"status_code":  statusCode,
			"latency_time": latencyTime,
			"client_ip":    ClientIp,
			"req_method":   reqMethod,
			"req_uri":      reqUri,
		})
		if len(c.Errors) > 0 {
			entry.Error(c.Errors.ByType(gin.ErrorTypePrivate).String())
		} else {
			msg := fmt.Sprintf("| %3d | %13v | %15s | %s | %s |",
				statusCode,
				latencyTime,
				ClientIp,
				reqMethod,
				reqUri)
			if statusCode >= http.StatusInternalServerError {
				entry.Error(msg)
			} else if statusCode >= http.StatusBadRequest {
				entry.Warn(msg)
			} else {
				entry.Info(msg)
			}
		}
	}
}

func Info(args ...interface{}) {
	logger.Info(args)
}
func Infoln(args ...interface{}) {
	logger.Infoln(args)
}

func Infof(format string, args ...interface{}) {
	logger.Infof(format, args)
}

func Warn(format string, args ...interface{}) {
	logger.Warn(format, args)
}

func Error(format string, args ...interface{}) {
	logger.Error(format, args)
}

func Errorf(format string, args ...interface{}) {
	logger.Errorf(format, args)
}

func Fatalf(format string, args ...interface{}) {
	logger.Fatalf(format, args)
}

func Errorln(format string, args ...interface{}) {
	logger.Errorln(format, args)
}
